package com.community.owner.controller;

import java.io.IOException;
import java.util.List;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.listener.PageReadListener;
import com.community.common.utils.minio.MinioUtils;
import com.community.owner.domain.enums.SmartCode;
import com.community.owner.domain.vo.OwnerAddRequest;
import com.community.owner.domain.vo.OwnerVo;
import com.community.owner.domain.vo.Result;
import com.community.owner.handle.exception.MyException;
import io.minio.BucketExistsArgs;
import io.minio.MinioClient;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.community.common.annotation.Log;
import com.community.common.core.controller.BaseController;
import com.community.common.core.domain.AjaxResult;
import com.community.common.enums.BusinessType;
import com.community.owner.domain.Owner;
import com.community.owner.service.OwnerService;
import com.community.common.utils.poi.ExcelUtil;
import com.community.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 业主信息Controller
 * 
 * @author ruoyi
 * @date 2025-10-25
 */
@RestController
@RequestMapping("/owner/owner")
public class OwnerController extends BaseController
{
    @Autowired
    private OwnerService ownerService;

    /**
     * 统计业主数量
     */
    @GetMapping("/count")
    public AjaxResult count(){
        return success(ownerService.count());
    }

    /**
     * 查询业主信息列表
     */
    @PreAuthorize("@ss.hasPermi('owner:owner:list')")
    @GetMapping("/list")
    public TableDataInfo list(Owner owner)
    {
        startPage();
        List<Owner> list = ownerService.selectOwnerList(owner);
        return getDataTable(list);
    }

    /**
     * 导出业主信息列表
     */
    @PreAuthorize("@ss.hasPermi('owner:owner:export')")
    @Log(title = "业主信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Owner owner)
    {
        List<Owner> list = ownerService.selectOwnerList(owner);
        ExcelUtil<Owner> util = new ExcelUtil<Owner>(Owner.class);
        util.exportExcel(response, list, "业主信息数据");
    }

    /**
     * 获取业主信息详细信息
     */
    @PreAuthorize("@ss.hasPermi('owner:owner:query')")
    @GetMapping(value = "/{ownerId}")
    public AjaxResult getInfo(@PathVariable("ownerId") Long ownerId)
    {
        return success(ownerService.selectOwnerByOwnerId(ownerId));
    }

    /**
     * 新增业主信息
     */
    //@PreAuthorize("@ss.hasPermi('owner:owner:add')")
    @Log(title = "业主信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Owner owner)
    {
        return toAjax(ownerService.insertOwner(owner));
    }

    /**
     * 修改业主信息
     */
    @PreAuthorize("@ss.hasPermi('owner:owner:edit')")
    @Log(title = "业主信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Owner owner)
    {
        return toAjax(ownerService.updateOwner(owner));
    }

    /**
     * 删除业主信息
     */
    @PreAuthorize("@ss.hasPermi('owner:owner:remove')")
    @Log(title = "业主信息", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ownerIds}")
    public AjaxResult remove(@PathVariable Long[] ownerIds) {
        int result = ownerService.deleteOwnerByOwnerIds(ownerIds);
        if (result > 0) {
            return AjaxResult.success(SmartCode.DELETE_SUCCESS.getMsg());
        } else {
            return AjaxResult.error(SmartCode.DELETE_USER_ERROR3.getMsg());
        }
    }

    /**
     * 获取业主信息详细信息
     */
    @PreAuthorize("@ss.hasPermi('owner:owner:query')")
    @GetMapping(value = "/detail/{ownerId}")
    public AjaxResult getDetail(@PathVariable("ownerId") Long ownerId) {
        Owner owner = ownerService.selectOwnerWithDetailsByOwnerId(ownerId);
        if (owner == null) {
            return AjaxResult.error("业主不存在");
        }
        return AjaxResult.success(owner);
    }


    /**
     * 查询业主列表（分页）
     */
    /**
     * 查询业主列表（分页）
     */
    //@PreAuthorize("@ss.hasPermi('owner:owner:resident')")  // 使用已有的权限
    @GetMapping(value = "/selectOwnerVoList")
    public TableDataInfo selectOwnerVoList(OwnerVo ownerVo) {
        startPage();
        List<OwnerVo> list = ownerService.selectOwnerVoList(ownerVo);
        return getDataTable(list);
    }

    @Autowired
    private MinioUtils  minioUtils;

    @Autowired
    private MinioClient minioClient;


    //上传excel文件
    @PostMapping("/upload")
    public Result<?> upload(@RequestParam("file") MultipartFile file) throws IOException {
        try {
            //读取收到的这个excel文件//将里面数据解析出来
            EasyExcel.read(file.getInputStream(), Owner.class, new PageReadListener<Owner>(data ->
                    ownerService.addPermsByFile(data)

            )).sheet().doRead();
            //批量新增
            return Result.ok(null, SmartCode.SAVE_PERMISSION_SUCCESS.getMsg());
        } catch (IOException e) {
            return Result.fail(SmartCode.SAVE_ERROR.getMsg()+ e.getMessage());
        }
    }


    @GetMapping("/downloadOwnerModel/{ownerList}")
    public ResponseEntity<byte[]> downloadOwnerModel(@PathVariable("ownerList") String ownerList) {
        try {
            ResponseEntity<byte[]> fileResponse = minioUtils.download(ownerList);

            // 添加自定义响应头
            HttpHeaders headers = new HttpHeaders();
            headers.add("X-Download-Filename", ownerList);
            headers.add("X-Download-Message", "文件下载成功");
            headers.add("Access-Control-Expose-Headers", "X-Download-Filename, X-Download-Message");

            return ResponseEntity.ok()
                    .headers(headers)
                    .body(fileResponse.getBody());

        } catch (Exception e) {
            throw new MyException(Result.fail(SmartCode.SAVE_DOWNLOAD_ERROR.getMsg() + e.getMessage()));
        }
    }

    @PostMapping("/addOwnerWithUser")
    public AjaxResult addOwnerWithUser(@RequestBody OwnerAddRequest request) {
        try {
            ownerService.addOwnerWithUser(request);
            return AjaxResult.success(SmartCode.SAVE_SUCCESS.getMsg());
        } catch (Exception e) {
            return AjaxResult.error(SmartCode.SAVE_ERROR.getMsg());
        }
    }

}
